package com.example.pertecttime.base;

import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;

/**
 * 用于管理RxBus的事件和RxJava相关代码的生命周期处理
 * Created by hp on 2016/8/13.
 */
public class RxManager {
    public RxBus rxBus = RxBus.getInstance();
    //管理观测源
    private Map<String, Observable<?>> observables = new HashMap<>();
    //管理订阅者
    private CompositeSubscription compositeSubscription = new CompositeSubscription();

    public void on(String eventName, Action1<Object> action1){
        Observable<?> observable = rxBus.register(eventName);
        observables.put(eventName,observable);
        compositeSubscription.add(observable.observeOn(AndroidSchedulers.mainThread())
        .subscribe(action1,(e) -> e.printStackTrace()));
    }
    //带返回参数
    public Observable on1(String eventName,Action1<Object> action1){
        Observable<?> observable = rxBus.register(eventName);
        observables.put(eventName,observable);
        compositeSubscription.add(observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(action1,(e) -> e.printStackTrace()));
        return observable;
    }
    public void unregister(String eventName, Observable<?> observable){
        rxBus.unregister(eventName,observable);
    }

    public void add(Subscription m){
        compositeSubscription.add(m);
    }

    public void clear(){
        //取消订阅
        compositeSubscription.unsubscribe();
        for(Map.Entry<String,Observable<?>> entry : observables.entrySet()){
            //移除观察
            rxBus.unregister(entry.getKey(),entry.getValue());
        }
    }

    public void post(Object tag,Object content){
        rxBus.post(tag,content);
    }


}
